package com.jingdianjichi.wx.handler;

import com.jingdianjichi.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.message.Message;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * ClassName:ReceiveTextMsgHandler
 * Package:com.jingdianjichi.wx.handler
 * Description:
 *
 * @Author fst
 * @Create 2024/10/15 21:59
 * @Version 1.0
 */
@Component
@Slf4j
public class ReceiveTextMsgHandler implements WxChatMsgHandler
{
    @Resource
    private RedisUtil redisUtil;

    private static final String LOGIN_PREFIX ="loginCode";
    @Override
    public WxChatMsgTypeEnum getMsgType() {
        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> msgmap) {
        log.info("信息回复");

        String content = msgmap.get("Content");

        if(!"验证码".equals(content))
        {
            return "";
        }

        String fromUserName = msgmap.get("FromUserName");
        String toUserName = msgmap.get("ToUserName");

        Random random = new Random();
        int num =random.nextInt(1000);
        String respond ="您当前的验证码是："+num+","+"五分钟内有效";

        String numKey = redisUtil.buildKey(LOGIN_PREFIX,String.valueOf(num));

        redisUtil.setNx(numKey,fromUserName,5L, TimeUnit.MINUTES);

        String replyContent="<xml>" +
                "<ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
                "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                "<CreateTime>12345678</CreateTime>\n" +
                "<MsgType><![CDATA[text]]></MsgType>\n" +
                "<Content><![CDATA["+respond+"]]></Content>\n"+
                "</xml>";

        log.info("replyContent:{}",replyContent);
        return replyContent;
    }
}
